using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Collections; 

namespace OvernightForRecaluateQty
{
    public partial class frmImRecalQty : Form
    {

        private string mstrFieldName = "C:\\Program Files\\WoodPro Software Inc\\WoodPro InSight" + "\\ImRecalcQty.XmL";
            
        public frmImRecalQty()
        {
            InitializeComponent();
        }               

        private void Recal(string strConDB )
        {
            DBAccess.ConnectionDBString =strConDB ;
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                bool mblnNeedCalcBackOrder = chkCalBackOrder.Checked;
                bool mblnNeedCalcCommitted = chkCalCommitted.Checked;
                bool mblnNeedCalcOeReturn = chkCalOeReturn.Checked;
                bool mblnNeedCalcOnHand = chkCalOnHand.Checked;
                bool mblnNeedCalcOnOrder = chkCalOnOrder.Checked;
                bool mblnNeedCalcReman = chkCalReman.Checked;
                bool mblnNeedCalcTagLot = chkCalTagLot.Checked;
                bool mblnNeedCalcTrasfer = chkCalTransfer.Checked;
                bool mblnNeedCalcImAdjQty = chkCalAdjQty.Checked;
                bool mblnNeedCalcQuoteRemaining = chkCalQuoteRemaining.Checked;

                Type[] ptype = null;
                Type typeRecal = null;
                ptype = new Type[11];
                ptype.SetValue(typeof(string), 0);    
                ptype.SetValue(typeof(bool), 1);
                ptype.SetValue(typeof(bool), 2);
                ptype.SetValue(typeof(bool), 3);
                ptype.SetValue(typeof(bool), 4);
                ptype.SetValue(typeof(bool), 5);
                ptype.SetValue(typeof(bool), 6);
                ptype.SetValue(typeof(bool), 7);
                ptype.SetValue(typeof(bool), 8);
                ptype.SetValue(typeof(bool), 9);
                ptype.SetValue(typeof(bool), 10);                


                typeRecal = Type.GetType("WP.IM.DataAccess.ImRecalculateItemQtyDAL," + "WP.IM.DataAccess", true, true);
                if (typeRecal != null)
                {
                    object oRpt = Activator.CreateInstance(typeRecal);
                    MethodInfo mInfo = oRpt.GetType().GetMethod("RecalcQtyFromOvernight", ptype);
                    object[] Param = {strConDB , mblnNeedCalcBackOrder, mblnNeedCalcOnOrder, mblnNeedCalcReman,
                    mblnNeedCalcTrasfer, mblnNeedCalcCommitted, mblnNeedCalcOnHand,
                    mblnNeedCalcTagLot, mblnNeedCalcOeReturn, mblnNeedCalcImAdjQty, mblnNeedCalcQuoteRemaining };
                    if (mInfo != null)
                    {
                        object obj = mInfo.Invoke(oRpt, Param);
                        obj = null; 
                    }
                }
                string strCon = " Overnight Recalculate finished.";
                string strSQL = " Insert into mLog ( Remark,USys,UDate,Utime ) " +
                                " VALUES ('{0}','{1}','{2}','{3}')";
                strSQL = string.Format(strSQL, strCon, "IM",DateTime.Now,DateTime.Now.Hour + ":" + DateTime.Now.Minute    );
                dbcon.ExecuteSql(strSQL);

                typeRecal = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
            }
            
            dbcon.CloseCon();
        }

        private void LoadConfigTxt()
        {
            bool blnNew = false ;           

            string strFileName = mstrFieldName;
            string strPathName = mstrFieldName.Replace("\\ImRecalcQty.XmL", "");

            if (!Directory.Exists(strPathName))
            {
                strPathName = strPathName.Replace("Program Files", "Program Files (x86)");

                if (!Directory.Exists(strPathName))
                {
                    return;
                }
            }
            strFileName = strPathName + "\\ImRecalcQty.XmL";
            mstrFieldName = strFileName;
            if (!File.Exists(mstrFieldName)) return;  

             DataTable dtTable = new DataTable();
             dtTable.ReadXml( strFileName );
             foreach (DataRow drRow in dtTable.Rows)
             {
                 chkCalTransfer .Checked =Convert.ToBoolean( drRow["CalcTransfer"] );
                 chkCalTagLot.Checked =Convert.ToBoolean( drRow["CalcTagLot"]);
                 chkCalReman.Checked =Convert.ToBoolean( drRow["CalcReman"] );
                 chkCalQuoteRemaining .Checked = Convert.ToBoolean(drRow["CalcQuoteRemain"] ) ;
                 chkCalOnOrder .Checked = Convert.ToBoolean(drRow["CalcOnOrder"]) ;
                 chkCalOnHand .Checked = Convert.ToBoolean(drRow["CalcOnhand"]) ;
                 chkCalOeReturn .Checked = Convert.ToBoolean(drRow["CalcReturn"]) ;
                 chkCalEfftAvgCost .Checked = Convert.ToBoolean(drRow["CalcEffectWtAvgcost"]) ;
                 chkCalCommitted .Checked = Convert.ToBoolean(drRow["CalcCommitted"]) ;
                 chkCalBackOrder .Checked = Convert.ToBoolean(drRow["CalcBackOrder"]) ;
                 chkCalAdjQty.Checked = Convert.ToBoolean(drRow["CalcAdjust"]) ;
                 txtRunTime.Text = drRow["StartTime"].ToString();
                 ArrayList arrListServerAndDB= new ArrayList ();
                 string strUserName = string.Empty;
                 string strPwd = string.Empty;
                 AnalysConStr(drRow["ConnectString"].ToString(),ref  arrListServerAndDB , ref strUserName,ref strPwd );
                 foreach ( string strServerAndDB in arrListServerAndDB )
                 {
                     if ( txtServerName.Text =="")
                        txtServerName.Text = strServerAndDB  ; 
                     else
                        txtServerName.Text +="\r\n" + strServerAndDB; 
                 }
                 txtUserName.Text = strUserName;
                 txtPWD.Text = strPwd;                
             }            
        }

        private void AnalysConStr(string strConStr, ref ArrayList arrListServerAndDB,ref string strUserName , ref string strPwd )
        {
            //data source=Boserver1\SQL2005;database=RTBP20090902;Connect Timeout=90;uid=procom;pwd=2W00dpr00;
            string[] strServerandDB = strConStr.Split(new string[] { "\r\n" } , StringSplitOptions.RemoveEmptyEntries);
            if (strConStr != "" && strServerandDB.Length == 0)
            {
               
            }
            else
                for (int i = 0; i < strServerandDB.Length; i++)
                {
                    string strServerName = strServerandDB[i].Split(new char[] { ';' })[0];
                    strServerName = strServerName.Replace("data source=", ""); 
                    string strDBName = strServerandDB[i].Split(new char[] { ';' })[1];
                    strDBName = strDBName.Replace("database=", "");
                    arrListServerAndDB.Add(strServerName + ";" + strDBName);
                    
                    strUserName= strServerandDB[i].Split(new char[] {';'})[3];  
                    strUserName = strUserName.Replace("uid=","");                     
                    strPwd= strServerandDB[i].Split(new char[] {';'})[4];
                    strPwd = strPwd.Replace("pwd=", "");
                }            
        }
        
        private bool VaildCheck()
        {            
            if (txtServerName.Text == "")
            {
                MessageBox.Show("Please set the server and database name.", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            try
            {
                string[] strServerandDB = txtServerName.Text.Split(new string[] { "\r\n" } , StringSplitOptions.RemoveEmptyEntries);
                if ((strServerandDB.Length) <= 0)
                {
                }
                else
                {
                    for (int i = 0; i < strServerandDB.Length; i++)
                    {
                        string strServerName = strServerandDB[i].Split(new char[] { ';' })[0];
                        string strDBName = strServerandDB[i].Split(new char[] { ';' })[1];
                        string strConDB = "data source=" + strServerName + ";database=" + strDBName + ";Connect Timeout=20;Trusted_Connection=yes;";
                        try
                        {
                            DBAccess.ConnectionDBString = strConDB;
                            DBAccess dbcon = new DBAccess(false, false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Please reset servername and database.", "" ,MessageBoxButtons.OK, MessageBoxIcon.Warning  );
                            return false;
                        }
                    }
                }   
            }
            catch (Exception ex)
            {
                return false;
            }

            if (txtRunTime.Text == "")
            {
                MessageBox.Show("Please set the Overnight Run Time", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            try
            {

                DateTime dt;
                if (DateTime.TryParse(txtRunTime.Text, out dt))
                {
                    return true;
                }
                else
                {
                    MessageBox.Show("Please reinput the Run Time.", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            }
            catch ( Exception ex)
            {
                MessageBox .Show ( "Please reinput the Run Time.","", MessageBoxButtons .OK , MessageBoxIcon .Warning );
                return false ;
            }

            return true;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (UpdateData())
            {
                this.Close();
                Application.Exit();
            }
        }
        
        private bool UpdateData()
        {
            if (!VaildCheck()) return false;            
            if (txtServerName.Text == "")
            {
                MessageBox.Show("Please input the server name and database name.");
            }
            else
            {
                string[] strServerandDB = txtServerName.Text.Split(new string[] { "\r\n" } , StringSplitOptions.RemoveEmptyEntries);
                if ((strServerandDB.Length) <= 0)
                {
                }
                else
                {
                    string strConDB=string.Empty ;
                    for (int i = 0; i < strServerandDB.Length; i++)
                    {
                        string strServerName = strServerandDB[i].Split(new char[] { ';' })[0];
                        string strDBName = strServerandDB[i].Split(new char[] { ';' })[1];
                        if ( strConDB =="")
                            strConDB=@"data source="+ strServerName +";database="+ strDBName +";Connect Timeout=90;uid="+ txtUserName.Text +";pwd="+ txtPWD.Text +";";                        
                        else
                            strConDB +="\r\n" + @"data source=" + strServerName + ";database=" + strDBName + ";Connect Timeout=90;uid="+ txtUserName.Text +";pwd="+ txtPWD.Text +";";                        
                    }
                    DataTable dtRecalItemQty = new DataTable("ImRecalcQty");
                    dtRecalItemQty.Columns.Add(new DataColumn("ConnectString", typeof(string)));
                    dtRecalItemQty.Columns.Add(new DataColumn("StartTime", typeof(string)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcBackOrder", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcOnhand", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcCommitted", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcReman", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcTransfer", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcOnOrder", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcTagLot", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcReturn", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcAdjust", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcEffectWtAvgcost", typeof(bool)));
                    dtRecalItemQty.Columns.Add(new DataColumn("CalcQuoteRemain", typeof(bool)));
                                        
                    dtRecalItemQty.Rows.Add();
                    DataRow dr = dtRecalItemQty.Rows[0];
                    dr["ConnectString"] = strConDB  ;
                    dr["StartTime"] =  txtRunTime.Text  ;
                    dr["CalcBackOrder"] = chkCalBackOrder.Checked  ;
                    dr["CalcOnhand"] = chkCalOnHand.Checked    ;
                    dr["CalcCommitted"] = chkCalCommitted.Checked    ;
                    dr["CalcReman"] = chkCalReman.Checked    ;
                    dr["CalcTransfer"] = chkCalTransfer.Checked   ;
                    dr["CalcOnOrder"] = chkCalOnOrder.Checked    ;
                    dr["CalcTagLot"] = chkCalTagLot.Checked    ;
                    dr["CalcReturn"] = chkCalOeReturn.Checked   ;
                    dr["CalcAdjust"] = chkCalAdjQty.Checked   ;
                    dr["CalcEffectWtAvgcost"] = chkCalEfftAvgCost.Checked;
                    dr["CalcQuoteRemain"] = chkCalQuoteRemaining.Checked;
                    dtRecalItemQty.AcceptChanges();
                    if (File.Exists(mstrFieldName)) File.Delete(mstrFieldName);                      
                    dtRecalItemQty.WriteXml(mstrFieldName, XmlWriteMode.WriteSchema, false);
                    
                }
            }
            return true;
        }
        
        private void btnRun_Click(object sender, EventArgs e)
        {
            //if (!UpdateData()) return;
            //this.Hide(); 
            //loop:
            //if (DateTime.Parse(txtRunTime.Text).Hour == DateTime.Now.Hour && DateTime.Parse(txtRunTime.Text).Minute == DateTime.Now.Minute )
            //{
            //    string[] strServerandDB = txtServerName.Text.Split(new string[] { "\r\n" } , StringSplitOptions.RemoveEmptyEntries);
            //    if ((strServerandDB.Length) <= 0)
            //    {
            //    }
            //    else
            //    {
            //        for (int i = 0; i < strServerandDB.Length; i++)
            //        {
            //            string strServerName = strServerandDB[i].Split(new char[] { ';' })[0];
            //            string strDBName = strServerandDB[i].Split(new char[] { ';' })[1];
            //            string strConDB = "data source=" + strServerName + ";database=" + strDBName + ";Connect Timeout=90;Trusted_Connection=yes;";
            //            try
            //            {
            //                Recal(strConDB);
            //            }
            //            catch (Exception ex)
            //            {
            //                MessageBox.Show(ex.ToString());
            //            }
            //        }
            //    }               
            //}    
            //else
            //    System.Threading.Thread.Sleep(50000);

            //goto loop;
               
        }

        private void frmImRecalQty_Load(object sender, EventArgs e)
        {
            LoadConfigTxt();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }
    }
}
